/*
 * @Author: 瞿旺兴 18774621495@163.com
 * @Date: 2022-05-25 15:55:06
 * @LastEditors: 瞿旺兴 18774621495@163.com
 * @LastEditTime: 2022-06-23 09:32:52
 * @FilePath: \nien-vue3-admin\src\store\modules\websocket.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user'
import CreateWebsocket from '@/utils/websocket'

let socket = null
// const socket = new CreateWebsocket('ws://192.168.1.78:8081/system/websocket/message/liuyb')
// // 订阅队列
// // 返回消息分两类
// // sign 为应答消息  msgType 为 sign类型最新消息
const queue:Array<{type: {sign?:string, msgType?: string}, callback:(data)=>void}> = []
// socket.message = (e) => {
//   const data = JSON.parse(e.data) 
//   for (const { type, callback } of queue) {
//     if ((type.sign && (type.sign === data.sign)) || (type.msgType && (type.msgType === data.msgType))) {
//       callback && callback(data)
//     }
//   }
// }
const useWsStore = defineStore('wsStore', {
  state() {
    return {
      SIGN_MAP: {
        EXCEPTION_PREFIX: 'exceptionPrefix', // 异常通知
        CUT_ORDER_PUSH: 'cutOrderPush', // 空海运截单提醒
        INDEX_REPORT: 'indexReport', // 首页报表
        LINE_CHART_PUSH: 'lineChartPush', // 首页线形图
        COLUMNAR_CHART_PUSH: 'columnarChartPush', // 首页柱状图
        WORK_NOTICE_PUSH: 'workNoticePush', // 工作通知推送
        TODO_NOTICE_PUSH: 'toDoNoticePush', // 待审批通知推送
        APPROVAL_NOTICE_PUSH: 'approvalNoticePush', // 已审批
        MORE_PAYMENT_NOTICE_PUSH: 'morePaymentNoticePush', // 账单超账期异常
        BILL_NOT_PUSH: 'billNotPush', // 账单已出单未推送（2天）
        UNVERIFICATION_BILL_PUSH: 'unVerificationBillPush', // 账单已回款未核销（2天）
        ORDER_ABNORMAL_NOTICE_PUSH: 'orderAbnormalNoticePush', // 订单异常通知
        WAREHOUSE_ALLOT_NOTICE_PUSH: 'warehouseAllotNoticePush', // 仓库分配异常通知
        FINANCE_BILL_PUSH: 'financeBillPush', // 财务账单提醒
        CUST_BILL_PUSH: 'custBillPush', // 客户端账单提醒
        LOWER_ORDER_PUSH: 'lowerOrderPush', // 订单制单提醒

      },
      MSG_TYPE_MAP: {
        TODO_NOTICE: 'toDoNotice', // 待审批最新消息
        WORK_NOTICE: 'workNotice', // 工作最新消息
        MORE_PAYMENT_NOTICE: 'morePaymentNotice', // 超账期未结算最新消息
        BILL_NOT_PUSH_NOTICE: 'billNotPushNotice', // 已出单未推送(2天)最新消息
        UNVERIFICATION_NOTICE: 'unVerificationNotice', // 待审批最新消息
        ORDER_ABNORMAL_NOTICE: 'orderAbnormalNotice', // 订单异常最新消息
      },
    }
  },
  actions: {
    send(sign:string, params = {}) {
      if (!sign) {
        return 
      }
      const userStore = useUserStore()
      const data = {
        // Authorization: 'Bearer 937438f5-d990-4d9b-a358-95c70817b35f',
        Authorization: `Bearer ${ userStore.token }`,
        sign,
        // userName: 'liuyb',
        userName: userStore.user.userName,
        params,
      }
      if (!params || !Object.keys(params)?.length) {
        delete data.params
      }
      
      if (socket) {
        socket.send(JSON.stringify(data))
      } else {
        ElMessage.error('Websocket未连接！')
      }
    },
    onMessage(type: {sign?:string, msgType?: string}, callback:(data)=>void) {
      queue.push({ type, callback })
    },
    initWs() {
      if (!socket) {
        const userStore = useUserStore()
        if (!userStore?.user?.userName) return
        socket = new CreateWebsocket(import.meta.env.VITE_WS + userStore.user.userName)
        socket.message = (e) => {
          const data = JSON.parse(e.data) 
          for (const { type, callback } of queue) {
            if ((type.sign && (type.sign === data.sign)) || (type.msgType && (type.msgType === data.msgType))) {
              callback && callback(data)
            }
          }
        }
      } else if (socket.status === 'CLOSED') {
        socket.init()
      }
    },
  },
})

export default useWsStore